#include "StreamSocket.h"

void StreamSocket::Connect( ptree& cfg ) {
	
	string host, service;
	
	if(( host = cfg.get("host", "localhost" )) == "localhost" )
	{
		printf("warningsss\n");
	}
	
	if(( service = cfg.get("service", "http" )) == "http" )
	{
		printf("warningsss\n");
	}
	
	Resolver.async_resolve( tcp::resolver::query( host, service ), 
		boost::bind( &StreamSocket::ResolveHdlr, this, boost::asio::placeholders::error, boost::asio::placeholders::iterator ));
}

void StreamSocket::ResolveHdlr( const boost::system::error_code& error, tcp::resolver::iterator endp ) {
    
	if ( error ) return OnConnect( error );

	Socket.async_connect( *endp, boost::bind( &StreamSocket::ConnectHdlr, this, boost::asio::placeholders::error ));
}

void StreamSocket::ConnectHdlr( const boost::system::error_code& error ) {
	
	if( !error )
	{
		Socket.async_receive( boost::asio::buffer( Buffer.data(), 128), boost::bind(&StreamSocket::OnReceive, this, boost::asio::placeholders::error ));	
	}
	
	OnConnect( error );
}

// size_t StreamSocket::ReceiveHdlr( const boost::system::error_code& error ) {
// }

// {
//     tcp::endpoint EndPoint = *EndPointIter;
// 
//     Socket.async_connect(EndPoint,
//             boost::bind(&StreamSocket::OnConnect, this, boost::asio::placeholders::error, ++EndPointIter));
// }

// void StreamSocket::Close() {
//     IO.post( boost::bind( &StreamSocket::DoClose, this ));
// }
// 
// void StreamSocket::OnConnect( const boost::system::error_code& ErrorCode, tcp::resolver::iterator EndPointIter)
// {
// 	printf("HEllo %d", ErrorCode );
//     if (ErrorCode == 0)
//     // Successful connected
//     {
//         Socket.async_receive(boost::asio::buffer(m_Buffer.data(), m_BufLen),
//                 boost::bind(&StreamSocket::OnReceive, this, boost::asio::placeholders::error));
// 
// 
//     } else if (EndPointIter != tcp::resolver::iterator())
//     {
//         Socket.close();
//         tcp::endpoint EndPoint = *EndPointIter;
// 
//         Socket.async_connect(EndPoint,
//                 boost::bind(&StreamSocket::OnConnect, this, boost::asio::placeholders::error, ++EndPointIter));
//     }
// }
// 
// void StreamSocket::OnReceive(const boost::system::error_code& ErrorCode)
// {
//     if (ErrorCode == 0)
//     {
//         std::cout << m_Buffer.data() << std::endl;
// 
//         Socket.async_receive(boost::asio::buffer(m_Buffer.data(), m_BufLen),
//                 boost::bind(&StreamSocket::OnReceive, this, boost::asio::placeholders::error));
//     } else {
//         DoClose();
//     }
// }
// 
// void StreamSocket::DoClose()
// {
//     Socket.close();
// }
